<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
import echarts from 'echarts'

require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '400px'
    },
    datas: {
      default: 123
    },
    options: {
      type: Object
    },
    range: {
      type: Array,
      default: () => {
        const date = new Date()
        const array = []
        let range
        range = date.getFullYear() + '-' + (date.getMonth() + 1)
        array.push(range)
        return array
      }
    }
  },
  data() {
    return {
      chart: null

    }
  },
  computed: {
    newData() {
      return this.datas
    }
  },
  watch: {
    newData(val1, val2) {
      console.log(val1)
      if (this.chart) {
        console.log(this.chart, 'chart存在')
        this.chart.setOption(val1)
      } else {
        console.log(this.chart, 'chart不存在')
        this.initChart(val1)
      }
    }
  },
  mounted() {
    this.initChart(this.options)
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)

    this.chart.on('click', this.console1)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart(options) {
      this.chart = echarts.init(this.$el, 'macarons')

      this.chart.setOption(options)
    },
    console1(val) {
      console.log(1, val)
    }

  }
}
</script>
